package com.xxc.exam.interceptor

import com.xxc.common.util.StringUtil
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class CorsInterceptor:HandlerInterceptor {

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {

        // 不使用*，自动适配跨域域名，避免携带Cookie时失效
        val origin = request.getHeader("Origin")
        if (StringUtil.isNotEmpty(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin)
        }

        // 自适应所有自定义头
        val headers = request.getHeader("Access-Control-Request-Headers")
        if (StringUtil.isNotEmpty(headers)) {
            response.setHeader("Access-Control-Allow-Headers", headers)
            response.setHeader("Access-Control-Expose-Headers", headers)
        }

        // 允许跨域的请求方法类型
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS,PATCH")
        // 预检命令（OPTIONS）缓存时间，单位：秒
        response.setHeader("Access-Control-Max-Age", "3600")
        // 明确许可客户端发送Cookie，不允许删除字段即可
        response.setHeader("Access-Control-Allow-Credentials", "true")
        return true
    }
}